package com.woodws.fresh.im.controller

import com.woodws.fresh.common.core.extra.log
import com.woodws.fresh.im.api.dto.ImMessageDto
import com.woodws.fresh.im.api.service.ImMessageService
import com.woodws.fresh.im.api.service.ImSessionService
import com.woodws.fresh.im.rsocket.UserClient
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.rsocket.RSocketRequester
import org.springframework.stereotype.Controller
import reactor.core.publisher.Mono
import java.time.LocalDateTime

@Controller
class ChatController(val imMessageService: ImMessageService,
                     val imSessionService: ImSessionService
) {

    @MessageMapping("send")
    fun send(message: ImMessageDto): Mono<Void> {
        message.status = "1"
        message.sendTime = LocalDateTime.now()
        imMessageService.save(message).success {
            val session = imSessionService.findByUserId(message.toId!!).data
            if(session != null){
                val receiverRequester = if(session.serverId != 1L){
                    UserClient.CLIENTS[session.serverId.toString()]
                }else{
                    UserClient.CLIENTS[message.toId.toString()]
                }
                receiver(receiverRequester!!, it!!)
            }
        }

        return Mono.empty()
    }

    @MessageMapping("receiver")
    fun receiver(receiverRequester : RSocketRequester, message: ImMessageDto): Mono<Void> {
        receiverRequester.route("/rsocket")
            .data(message)
            .retrieveMono(String::class.java)
            .doOnNext { s: String? ->
                imMessageService.updateStatusById(message.id!!, "3")
            }
            .subscribe()

        return Mono.empty()
    }
}